import modelExtend from 'dva-model-extend'
import { getInfo, updateAddress } from './services/dashboard'
import { model } from 'utils/model'
import pathToRegexp from 'path-to-regexp';
import { routerRedux } from 'dva/router';

export default modelExtend(model, {
  namespace: 'dashboard',
  state: {
    info: {},
    urlVisible: false,
    distributorVisible: false,
    currentDistributor: {},
    copyText: '复制'
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        const match = pathToRegexp('/dashboard').exec(pathname);
        if (match) {
          dispatch({ type: 'getInfo', payload: {} })
        }
      })
    }
  },
  effects: {
    * getInfo({
      payload
    }, { select, call, put, take }) {
      // yield take('app/initApp/@@end');
      const data = yield call(getInfo);
      yield put({
        type: 'getInfoSuccess',
        payload: {
          info: data.result
        }
      })
      // }
    },
    * direct({
      payload
    }, { select, call, put }) {
      yield put(routerRedux.push(`/financialAccountBalanceRecord/${payload}`));
    },
    * updateAddress({
      payload
    }, { select, call, put }) {
      yield call(updateAddress, payload.id, payload.params);
      const data = yield call(getInfo);
      yield put({
        type: 'getInfoSuccess',
        payload: {
          info: data.result
        }
      })
      yield put({
        type: 'getInfoSuccess',
        payload: {
          currentDistributor:{},
          distributorVisible:false
        }
      })
    }
  },
  reducers: {
    getInfoSuccess(state, { payload }) {
      return {
        ...state,
        ...payload
      }
    }
  }
})
